package com.test.redis;

import java.io.PrintStream;
import java.util.HashSet;
import java.util.Set;

import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;

public class JedisClusterFactoryBean
  implements FactoryBean<JedisCluster>, InitializingBean
{
  private String host;
  private String port;
  private String password;
  private JedisCluster jedisCluster;

  public JedisCluster getObject()
    throws Exception
  {
    return this.jedisCluster;
  }

  public Class<?> getObjectType()
  {
    return JedisCluster.class;
  }

  public boolean isSingleton()
  {
    return true;
  }

  public void afterPropertiesSet()
    throws Exception
  {
    System.out.println("Redis client connected " + this.host + ":" + this.port);

    String[] ipList = this.host.split("\\|");
    String[] portList = this.port.split("\\|");

    Set jedisClusterNodes = new HashSet();
    for (int i = 0; i < ipList.length; i++) {
      jedisClusterNodes.add(new HostAndPort(ipList[i], Integer.valueOf(portList[i]).intValue()));
    }
    this.jedisCluster = new JedisCluster(jedisClusterNodes);
  }

  public String getHost() {
    return this.host;
  }

  public void setHost(String host) {
    this.host = host;
  }

  public String getPort() {
    return this.port;
  }

  public void setPort(String port) {
    this.port = port;
  }

  public String getPassword() {
    return this.password;
  }

  public void setPassword(String password) {
    this.password = password;
  }
}